import React, { Component } from 'react'
import Base from './base';
import { connect } from 'react-redux';
import DigitButton from './calculator/digitButton';
import ACTIONS from '../../redux/action';
import OperationButton from './calculator/operationButton';

class Calculator extends Component {
    // 每三位加一个逗号
    state = {
        formater: Intl.NumberFormat('en-us')
    };
    format = number => {
        if (number === "") return "";
        const [integer, decimal] = number.split('.');
        if (decimal === undefined)
            return this.state.formater.format(integer);
        return `${this.state.formater.format(integer)}.${decimal}`
    }
    render() {
        return (
            <Base>
                计算器
                <div className='calculator'>
                    <div className="output">
                        <div className="last-output">
                            {this.format(this.props.lastOperand)}{this.props.operation}
                        </div>
                        <div className="current-output">
                            {this.format(this.props.currentOperand)}
                        </div>
                    </div>
                    <button onClick={this.props.clear} className='button-ac'>AC</button>
                    <button onClick={this.props.delete_digit}>Del</button>
                    <OperationButton operation={"÷"}/>
                    <DigitButton digit={"7"} />
                    <DigitButton digit={"8"} />
                    <DigitButton digit={"9"} />
                    <OperationButton operation={"×"}/>
                    <DigitButton digit={"4"} />
                    <DigitButton digit={"5"} />
                    <DigitButton digit={"6"} />
                    <OperationButton operation={"-"}/>
                    <DigitButton digit={"1"} />
                    <DigitButton digit={"2"} />
                    <DigitButton digit={"3"} />
                    <OperationButton operation={"+"}/>
                    <DigitButton digit={"0"} />
                    <DigitButton digit={"."} />
                    <button onClick={this.props.evaluate} className='button-equal'>=</button>
                </div>
            
            </Base>
        );
    }
}


const mapStateToProps = (state,props) => {
    return {
        // 当前输入
        currentOperand : state.currentOperand, 
        // 上个输入
        lastOperand : state.lastOperand,
        // 操作符
        operation: state.operation,
    }
}

const mapDispatchToProps = {
    // 删除上一位
    delete_digit: () => {
        return {
            type: ACTIONS.DELETE_DIGIT,
        }
    },
    // 清空
    clear: () => {
        return {
            type: ACTIONS.CLEAR,
        }
    },
    // 等于结果
    evaluate: () => {
        return {
            type: ACTIONS.EVALUATE,
            
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(Calculator);